﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using vITs.Site.Models.ActionModels;
using vITs.Site.Models.DataModels;
using vITs.Site.Models;

namespace vITs.Site.Controllers
{
    public class UserController : Controller
    {
        public ActionResult SignIn()
        {
            return this.View();
        }

        [HttpPost]
        public ActionResult SignIn(SignInModel model, string returnUrl)
        {
            if (this.ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.EmailAddress, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.EmailAddress, false);

                    if (this.Url.IsLocalUrl(returnUrl))
                    {
                        return this.Redirect(returnUrl);
                    }

                    return this.Redirect(FormsAuthentication.DefaultUrl);
                }
                else
                {
                    this.ModelState.AddModelError("", "Epostadressen och/eller lösenordet stämde inte");
                }
            }

            return this.View(model);
        }

        public ActionResult SignOut()
        {
            FormsAuthentication.SignOut();

            return this.Redirect(FormsAuthentication.LoginUrl);
        }

        [Authorize(Roles="Administratör")]
        [HttpGet]
        public ActionResult Index(Int32 Page = 1)
        {
            var users = from User u in new VitsDB().Users select u;

            return this.View(users);
        }

        [Authorize(Roles="Administratör")]
        [HttpGet]
        public ActionResult Create()
        {
            return this.View();
        }

        [Authorize(Roles = "Administratör")]
        [HttpPost]
        public ActionResult Create(UserDataModel udm)
        {
            if (this.ModelState.IsValid)
            {
                bool anyErrors = false;

                VitsDB db = new VitsDB();
                var user = db.Users.SingleOrDefault(u => u.EmailAddress == udm.EmailAddress);

                if (user != null)
                {
                    anyErrors = true;
                    this.ModelState.AddModelError("EmailAddress", "Epostadressen finns redan i systemet");
                }

                if (String.IsNullOrEmpty(udm.Password))
                {
                    anyErrors = true;
                    this.ModelState.AddModelError("Password", "Du måste ange ett lösenord");
                    this.ModelState.AddModelError("ConfirmPassword", " ");
                }

                if (!anyErrors)
                {
                    String password = Utilities.GeneratePasswordHash(udm.Password);

                    User u = new User()
                    {
                        EmailAddress = udm.EmailAddress,
                        Password = password,
                        GivenName = udm.GivenName,
                        Surname = udm.Surname
                    };

                    foreach (var roleId in udm.Roles)
                    {
                        Int32 id;
                        if (Int32.TryParse(roleId, out id))
                        {
                            var role = db.Roles.SingleOrDefault(r => r.RoleId == id);
                            if (role == null) continue;

                            u.Roles.Add(role);
                        }
                    }

                    db.AddToUsers(u);
                    if (db.SaveChanges() > 0)
                    {
                        return this.RedirectToAction("Index");
                    }
                    else
                    {
                        this.ModelState.AddModelError("", "Användaren kunde inte sparas.");
                    }
                }
            }

            return this.View(udm);
        }

        [Authorize(Roles = "Administratör")]
        [HttpGet]
        public ActionResult Edit(Int32 id)
        {
            var user = new VitsDB().Users.SingleOrDefault(u => u.UserId == id);
            if (user == null)
            {
                return this.RedirectToAction("Index");
            }

            UserDataModel udm = new UserDataModel()
            {
                UserId = user.UserId,
                EmailAddress = user.EmailAddress,
                GivenName = user.GivenName,
                Surname = user.Surname
            };

            List<String> roles = new List<string>();
            foreach (var role in user.Roles)
            {
                roles.Add(role.RoleId.ToString());
            }
            udm.Roles = roles.ToArray();

            return this.View(udm);
        }

        [Authorize(Roles = "Administratör")]
        [HttpPost]
        public ActionResult Edit(UserDataModel udm)
        {
            VitsDB db = new VitsDB();
            var user = db.Users.SingleOrDefault(u => u.UserId == udm.UserId);
            if (user == null) return this.RedirectToAction("Index");

            if (this.ModelState.IsValid)
            {
                bool anyErrors = false;

                if (user.EmailAddress != udm.EmailAddress)
                {
                    var otherUser = db.Users.SingleOrDefault(u => u.EmailAddress == udm.EmailAddress);
                    if (otherUser != null)
                    {
                        anyErrors = true;
                        this.ModelState.AddModelError("EmailAddress", "Epostadressen finns redan i systemet");
                    }
                }

                if (!anyErrors)
                {
                    user.EmailAddress = udm.EmailAddress;
                    user.GivenName = udm.GivenName;
                    user.Surname = udm.Surname;

                    if (!String.IsNullOrEmpty(udm.Password))
                    {
                        user.Password = Utilities.GeneratePasswordHash(udm.Password);
                    }

                    user.Roles.Clear();
                    foreach (var roleId in udm.Roles)
                    {
                        Int32 id;
                        if (Int32.TryParse(roleId, out id))
                        {
                            var role = db.Roles.SingleOrDefault(r => r.RoleId == id);
                            if (role != null)
                            {
                                user.Roles.Add(role);
                            }
                        }
                    }

                    db.SaveChanges();

                    return this.RedirectToAction("Index");
                }
            }

            return this.View(udm);
        }

        [Authorize(Roles = "Administratör")]
        [HttpGet]
        public ActionResult Delete(Int32 id)
        {
            VitsDB db = new VitsDB();
            var user = db.Users.SingleOrDefault(u => u.UserId == id);
            if (user != null)
            {
                db.Users.DeleteObject(user);
                db.SaveChanges();
            }

            return this.RedirectToAction("Index");
        }
    }
}
